<form class="layui-form seller-form" action="">
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">年度：</label>
            <div class="layui-input-inline" id="year_box">
                <select name="year" lay-filter="year" id="year" list="year_list" lay-search>
                    <option value=""></option>
                    <datalist  id="year_list" lay-search>
                        {volist name="yearList" id="yearList"}
                        <option value="{$yearList.id}">{$yearList.year}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">季度：</label>
            <div class="layui-input-inline" id="season_box">
                <select name="season" lay-filter="season" id="season" list="season_list" lay-search>
                    <option value=""></option>
                    <datalist  id="season_list" lay-search>
                        {volist name="seasonList" id="seasonList"}
                        <option value="{$seasonList.season_id}">{$seasonList.season_name}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">部/院：</label>
            <div class="layui-input-inline" id="dep_box">
                <select name="dep_id" lay-filter="dep_id" id="dep_id" list="dep_list" lay-search>
                    <option value=""></option>
                    <datalist  id="dep_list" lay-search>
                        {volist name="deptList" id="deptList"}
                        <option value="{$deptList.bmdm}">{$deptList.bmmc}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">专业：</label>
            <div class="layui-input-inline" id="specialty_box">
                <select name="specialty_id" lay-filter="specialty_id" id="specialty_id" lay-search>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">班级：</label>
            <div class="layui-input-inline" id="class_box">
                <select name="class_id" lay-filter="class_id" id="class_id" list="class_list" lay-search>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">方向：</label>
            <div class="layui-input-inline" id="dir_box">
                <select name="dir" lay-filter="dir" id="dir" list="dir_list" lay-search>
                    <option value=""></option>
                    <datalist  id="dir_list" lay-search>
                        {volist name="dirList" id="dirList"}
                        <option value="{$dirList.id}">{$dirList.name}</option>
                        {/volist}
                    </datalist>
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <button type="button" class="layui-btn layui-btn-sm" lay-submit lay-filter="search"><i class="iconfont icon-chaxun"></i>查询</button>
            <button type="button" class="layui-btn layui-btn-sm draw_return" id="draw_return"><i class="layui-icon">&#xe608;</i>退书</button>
            <button id="book_return_print" type="button" class="layui-btn layui-btn-sm print"><i class="layui-icon">&#xe66d;</i>打印</button>
        </div>
    </div>
</form>

<div class="table-body">
    <table id="bookdrawreturnTable" lay-filter="bookdrawreturnTable"></table>
</div>

<script>
    layui.use(['table', 'form', 'layer', 'laydate'], function () {
        var layer = layui.layer, table = layui.table, form = layui.form, date = layui.laydate;
        var selectedItem = null;
        //执行渲染
        table.render({
            elem: '#bookdrawreturnTable', //指定原始表格元素选择器（推荐id选择器）
            height: 'full-120',
            cellMinWidth: '80',
            page: 'true',
            limit: '20',
            id: 'bookdrawreturnTable',
            url: "{:url('BookCommon/returnNull')}",
            // url: "{:url('BookReturn/drawreturnindex')}",
            cols: [[ //标题栏
                { type: 'numbers' },
                { field: 'year', sort: true, title: '年度', width: 80, align: 'center' },
                { field: 'season', sort: true, title: '季度', width: 80, align: 'center' },
                { field: 'dep', sort: true, title: '部/院', width: 200, align: 'center' },
                { field: 'specialty', sort: true, title: '专业', width: 200, align: 'center' },
                { field: 'class', sort: true, title: '班级', width: 200, align: 'center' },
                { field: 'dir', sort: true, title: '方向', width: 80, align: 'center' },
                { field: 'num', sort: true, title: '数量', width: 80, align: 'center' },
                { field: 'return_reason', title: '退书原因', width: 200, align: 'center' }
            ]], //设置表头
            where: {"year":$("#year").val(), "season": $("#season").val(), "dir": $("#dir").val()} 
            //,…… //更多参数参考右侧目录：基本参数选项
        });

        //监听行单击事件（双击事件为：rowDouble）
        table.on('row(bookdrawreturnTable)', function(obj){
            //标注选中样式
            obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
            selectedItem = obj;
        });

        layui.use('form', function () {
            // 联动年度
            form.on('select(year)', function (data) {
                getClass(data);
            });

            // 联动专业  
            form.on('select(specialty_id)', function (data) {
                getClass(data);
            });

            // 联动部门
            form.on('select(dep_id)', function (data) {
                getSpecialty(data);
            });
        });

        // 得到专业
        function getSpecialty(data) {
            $.ajax({
                type: 'get',
                url: "{:url('BookCommon/getSpecicalties')}",
                data: 'bmdm=' + data.value,
                success: function(e) {
                    if(e.status) {
                        $("#specialty_id").empty();//清空下拉框的值
                        $('#specialty_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $("#class_id").empty();//清空下拉框的值
                        $('#class_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $.each(e.data.data, function (index, item) {
                            $('#specialty_id').append(new Option(item.zymc, item.zydm));// 下拉菜单里添加元素
                        });
                        layui.form.render("select");//重新渲染 固定写法
                    } else {
                        layer.msg(e.msg);
                    }
                }
            });
        };
        
        // 得到班级
        function getClass(data) { 
            var dept = $("#dep_id").val();
            var specialty_id = $("#specialty_id").val();
            var year = $("#year").val();
            var season = $("#season").val();

            $.ajax({
                type: 'get',
                url: "{:url('BookCommon/getClasses')}",
                data: {
                        "bmdm": dept,
                        "zydm": specialty_id,
                        "plan_year":  year,
                        "plan_season": season
                    },
                success: function(e) {
                    if(e.status) {
                        $("#class_id").empty();//清空下拉框的值
                        $('#class_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $.each(e.data.data, function (index, item) {
                            $('#class_id').append(new Option(item.plan_class_name, item.plan_class_id));// 下拉菜单里添加元素
                        });
                        layui.form.render("select");//重新渲染 固定写法
                    } else {
                        layer.msg(e.msg);
                    }
                }
            });
        };
        
        // 查询
        form.on('submit(search)', function (data) {
            table.reload('bookdrawreturnTable', {
                where: data.field,
                page: {curr: 1},
                url: "{:url('BookReturn/drawreturnindex')}",
            });
            return false;
        });

        // 退书
        $(document).on('click','.draw_return',function(){  
            $("#draw_return").addClass("layui-btn-disabled");
            $("#draw_return").attr("disabled", true);
            $.ajax({
                type:'get',
                url: "{:url('BookReturn/drawreturnreturn')}",
                success:function(e){              
                    $("#draw_return").removeClass("layui-btn-disabled");
                    $("#draw_return").removeAttr("disabled");
                    if ((e.hasOwnProperty('status') && !e.status) || (e.hasOwnProperty('code') && e.code == 0)) {
                        layer.msg(e.msg); return false;
                    }

                    window.box = layer.open({
                        type: 1,
                        content: e,
                        area: ['750px', '420px'],
                        title:'退书',
                        id: 'LAY_bookdrawreturn_return'  // 设定id，防止重复弹出
                        ,shadeClose: false
                    });
                }
            });
            return false;
        });

        // 确定退书
        form.on('submit(draw-return)',function(data){
            var year = data.field.return_year;
            var season = data.field.return_season;
            var dep_id = data.field.return_dep_id;
            var specialty_id = data.field.return_specialty_id;
            var class_id = data.field.return_class_id;
            var dir = data.field.dir;
            var num = data.field.num;
            var return_reason = data.field.return_reason;

            if(!year){
                layer.msg('年度不能为空！', {time: 1300});
                return false;
            }
            if(!season){
                layer.msg('季度不能为空！', {time: 1300});
                return false;
            }
            if(!dep_id){
                layer.msg('部/院不能为空！', {time: 1300});
                return false;
            }
            if(!specialty_id){
                layer.msg('专业不能为空！', {time: 1300});
                return false;
            }
            if(!class_id){
                layer.msg('班级不能为空！', {time: 1300});
                return false;
            }
            if(!dir){
                layer.msg('方向不能为空！', {time: 1300});
                return false;
            }
            if(!num){
                layer.msg('数量不能为空！', {time: 1300});
                return false;
            }
            if(parseInt(num) != num){
                layer.msg('数量必须是整数！', {time: 1300});
                return false;
            }
            if(num<=0){
                layer.msg('数量必须大于0！', {time: 1300});
                return false;
            }
            if(!return_reason){
                layer.msg('原因不能为空！', {time: 1300});
                return false;
            }
           
            layer.confirm('确定要退书吗?', {icon: 3, title:'提示'}, function(){
                JsPost("{:url('BookReturn/drawreturnreturn')}", data.field, 
                    function(res){
                        if(res.status){
                            layer.close(window.box);
                            
                            // 弹出询问是否立即打印
                            layer.open({
                                type: 1,
                                fixed: false, //不固定
                                title:'提示',
                                content: '<div style="padding: 20px 100px;">'+res.msg+', 是否立即打印退书单？</div>',
                                shade: 0.3,
                                btn: ['确定', '取消'],
                                yes: function(index, layero){
                                    layer.closeAll();
                                    printBookReturnInfo(res.data.data['0']);
                                }
                                ,btn2: function(){
                                    layer.closeAll();
                                }
                            });
                        
                            table.reload('bookdrawreturnTable', {
                                // where: data.field,
                                page: {curr: 1},
                                url: "{:url('BookReturn/drawreturnindex')}",
                            });
                        }else{  
                           
                            layer.msg(res.msg,{time:1300});
                        }
                    }
                )            
            });
        });

        function printBookReturnInfo(bookDrawInfo) {
            // 获取打印信息
            JsGet("{:url('BookPlan/getBookReturnInfoByBatchDrawId')}?id="+bookDrawInfo['id'], function (res) {
                if(res.status){
                    // 构造打印数据
                    var ip = '127.0.0.1';
                    var port = '12345';

                    if(ip==""||port==""){ 
                        layer.msg("ip,port不能为空", { time: 1300 }); 
                        return false;
                    }
                    
                    var msg = '{'
                        +'"method":"' + 'printreport' +'"'
                        +',"ReportType":"' + 'gridreport' +'"'  /*报表类型 gridreport fastreport reportmachine 为空 将默认为gridreport  */
                        +',"ReportName":"' + 'bookreturn.grf' +'"' /*报表文件名 测试报表 */

                        +',"ReportVersion":"' + '1' +'"' /*可选。报表版本, 为空则默认1  如果本地报表的版本过低 将从 ReportUrl 地址进行下载更新*/
                        +',"ReportUrl":"' + '' +'"' /*可选。为空 将不更新本地报表 , 如果本地报表不存在可以从该地址自动下载*/
                        //+',"ReportUrl":"' + 'http://localhost/test.grf' +'"' /*可选。为空 将不更新本地报表 , 如果本地报表不存在可以从该地址自动下载*/
                        +',"Copies":"' + '1' +'"' /*可选。打印份数，支持指定打印份数。默认1份,如果为零,不打印,只返回报表生成的pdf,jpg等文件*/
                        
                        +',"Duplex":"' + '0' +'"' /*可选。双面打印 默认 0 需要双面打印的时候,请设置 2 或者3 , 可设置 0 打印机默认 1 单页 2 水平 3 垂直*/
                        
                        //+',"PrinterName":"' + $("#PrinterS option:selected").text() +'"' /*可选。指定打印机，为空的话 使用默认打印机, 请在 控制面板 -> 设备和打印机 中查看您的打印机的名称 */
                        +',"PrinterName":""' /*可选。指定打印机，为空的话 使用默认打印机, 请在 控制面板 -> 设备和打印机 中查看您的打印机的名称 */
                        +',"PrintOffsetX":"' + '0' +'"' /*可选。打印右偏移，单位厘米。报表的水平方向上的偏移量，向右为正，向左为负。*/
                        +',"PrintOffsetY":"' + '0' +'"' /*可选。打印下偏移，单位厘米。 报表的垂直方向上的偏移量，向下为正，向上为负。*/
                        +',"Preview":"' + '0' +'"'  /*可选。是否预览，和主界面设置的效果一样 为空默认不预览,   0：不预览，1：预览(弹出导出的pdf,jpg等文件)。*/
                        +',"token":"' + 'aa' +'"' /*可选。只要token值在列表中 方可打印*/
                        +',"taskId":"' + '1234567' +'"' /*可选。多个打印任务同时打印时，根据该id确定返回的是哪个打印任务。 */
                        +',"exportfilename":"' + '' +'"'  /*可选。自定义 导出 文件名称 为空 或者 自定义名称 如 test */
                        +',"exportfiletype":"' + '' +'"'  /*可选。自定义 导出 文件格式 为空 或者 自定义名称 如 pdf  */

                        +',"Control": ['  ///*部件框，可选值：AsStaticBox ,AsMemoBox,AsRichTextBox,AsPictureBox (url或base64格式),AsBarcode*/
                                //静态框 AsStaticBox  综合文字框 AsMemoBox, RTF文本框 AsRichTextBox,图像框 AsPictureBox (url或base64格式), 条码二维码 AsBarcode*
                                            
                                +'{"type": "AsStaticBox", "name": "dep","value": "'+bookDrawInfo['dep']+'","required": false},'
                                +'{"type": "AsStaticBox", "name": "dir","value": "'+bookDrawInfo['dir']+'","required": false},'
                                +'{"type": "AsStaticBox", "name": "class","value": "'+bookDrawInfo['class']+'","required": false},'
                            +']'
                        
                        +',"Field": ['  ///*字段， type ftBlob (base64格式) ,ftString ftInteger ftBoolean, ftFloat, ftCurrency,ftDateTime,  size (ftString 设置为实际长度,其他的设置为0,例如 ftInteger ftBlob 等设置为0 ) 
                                
                                +'{"type": "ftString", "name": "xuhao","size": 255,"required": true},'
                                +'{"type": "ftString", "name": "jiaocai","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "chubanshe","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "ISBN","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "shuliang","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "danjia","size": 255,"required": false},'
                                +'{"type": "ftString", "name": "jine","size": 255,"required": false},' 
                                +'{"type": "ftString", "name": "beizhu","size": 255,"required": false},' 

                            +']'

                        +',"Data": [';  ///*数据行

                            $.each(res.data, function(index, item){
                                msg += '{"xuhao": "'+item['xuhao']+'", "jiaocai": "'+item['jiaocai']+'","chubanshe": "'+item['chubanshe']+'", "ISBN": "'+item['ISBN']+'", "shuliang": "'+item['shuliang']+'", "danjia": "'+item['danjia']+'","jine": "'+item['jine']+'","beizhu": "'+item['beizhu']+'"},'
                            })

                            msg +=']'
                            
                        msg += '}';
                    
                    jQuery.support.cors = true;
                    $.ajax({
                        async : false,
                        url : "http://"+ip+":"+port+"/",
                        type : "POST",
                        contentType: "application/x-www-form-urlencoded", //要这样设置  
                        dataType : "json",
                        crossDomain: true,
                        data : msg,
                        beforeSend: function (XMLHttpRequest) {
                        },
                        success: function(data){		
                            if(data.status=="ok"){
                                layer.msg("打印成功:"+data.data, { time: 1300 }); 
                                // 添加打印日志
                                printLog = {
                                    "func_type": 3
                                    ,"func_id": bookDrawInfo['id']
                                    ,"operator": {$userId}
                                    ,"content": "预发放退书"};
                                addPrintLog(printLog);
                            }else{
                                layer.msg("打印失败:"+data.data, { time: 1300 });
                            }
                        },
                        error: function(data){
                            layer.msg("连接HttpPrinter失败:"+JSON.stringify(data), { time: 1300 });
                        }
                    });
                }
            })
        }
        
        // 打印
        $(document).on('click','.print',function(){
            if(selectedItem == null || selectedItem.data.length==0){
                layer.msg('请先选择要打印的数据行！', { time: 1300 });
                flag = false;
                return false;
            }
            
            $('#book_return_print').addClass("layui-btn-disabled");
            $('#book_return_print').attr("disabled", true); 
            printBookReturnInfo(selectedItem.data);
            $('#book_return_print').removeClass("layui-btn-disabled");
            $('#book_return_print').removeAttr("disabled");
        });
    })
    
    // 添加打印日志
    function addPrintLog(data){
        JsPost("{:url('BookCommon/addPrintLog')}", data, function (res) {
            if(res.status){
            } else{
            }
            // layer.msg(res.msg);
        });
    }
    $("#year").val({$year});  // 年度：
    $("#season").val({$season});  // 季度：
    $("#dir").val(1);  // 默认方向：就业
</script>